package cn.wzvtc.ch9jpa.controller;

import cn.wzvtc.ch9jpa.entity.User;
import cn.wzvtc.ch9jpa.repository.UserRepository;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Optional;

@RestController
@RequestMapping("/user")
public class UserController {
    @Autowired
    private UserRepository userRepository;

    //新增
    @PostMapping("/add")
    public String add(User user) {
        userRepository.save(user);
        return "success";
    }


    //根据ID删除
    @PostMapping("/delete")
    public String delete(Long id) {
        userRepository.deleteById(id);
        return "success";
    }

    //修改
    @PostMapping("/update")
    public String update(User user) {
        userRepository.save(user);
        return "success";
    }

    //根据id查询
    @GetMapping("/selectbyid")
    public User selectById(Long id) {
        Optional<User> user = userRepository.findById(id);
        //判断是否有值，如有则返回，反之返回null
        if (user.isPresent()) {
            return user.get();
        } else {
            return null;
        }
    }

    //查询全部
    @GetMapping("/selectall")
    public List<User> selectAll() {
        List<User> users = userRepository.findAll();
        return users;
    }

    //批量新增
    @PostMapping("/adduserlist")
    public String addUserList(@RequestBody List<User> users) {
        userRepository.saveAll(users);
        return "success";
    }

    @PostMapping("/login")
    public String login(String userName, String password) {
        User user = userRepository.findByUserNameAndPassword(userName, password);
        if (user != null) {
            return "success";
        } else {
            return "fail";
        }
    }

}
